import { login } from '@/api/login'
import { getToken, getCIDCToken, setToken, setCIDCToken, removeToken, removeCIDCToken, removeJSESSIONID,removeData } from '@/utils/auth'
import {  getUseLoginByUsernameApi, logoutApi } from '@/api/idaas'

const user = {
  state: {
    token: getToken(),
    cidcToken: getCIDCToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    realname: '',
    userId: '',
    branchcodeName: '',
    branchcode: '',
    branchinnercode: '',
    baseBranchinnercode: '',
    primaryDeptName: '',
    workStations:[],
    baseDeptCode:'',  //工厂编码
    baseDeptId:'',    //工厂id
    baseDeptName:'',//工厂名称
    allList:[],
    permitList:[],
    treePermitList:[],
    adminDetail:null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_CIDC_TOKEN: (state, token) => {
      state.cidcToken = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_REALNAME: (state, realname) => {
      state.realname = realname
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_BRANCHCODENAME: (state, branchcodeName) => {
      state.branchcodeName = branchcodeName
    },
    SET_BRANCHCODE: (state, branchcode) => {
      state.branchcode = branchcode
    },
    SET_BRANCHINNERCODE: (state, branchinnercode) => {
      state.branchinnercode = branchinnercode
    },
    SET_BASEBRANCHINNERCODE: (state, baseBranchinnercode) => {
      state.baseBranchinnercode = baseBranchinnercode
    },
    SET_PRIMARYDEPTNAME: (state, primaryDeptName) => {
      state.primaryDeptName = primaryDeptName
    },
    SET_WORKSTATIONS:(state, workStations) => {
      state.workStations = workStations
    },
    SET_BASEDEPTCODE:(state, baseDeptCode) => {
      state.baseDeptCode = baseDeptCode
    },
    SET_BASEDEPTID:(state, baseDeptId) => {
      state.baseDeptId = baseDeptId
    },
    SET_BASEDEPTNAME:(state, baseDeptName) => {
      state.baseDeptName = baseDeptName
    },
    SET_ALL_LIST:(state, allList) => {
      state.allList = allList
    },
    PERMIT_LIST:(state, permitList) => {
      state.permitList = permitList
    },
    TREE_PERMIT_LIST:(state, treePermitList) => {
      state.treePermitList = treePermitList
    },
    SET_ADMIN_DETAIL(state, adminDetail) {
      state.adminDetail = adminDetail;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const grantType = userInfo.grantType
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid, grantType).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          setCIDCToken(res.cidcToken || '')
          commit('SET_CIDC_TOKEN', res.cidcToken || '')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUseLoginByUsernameApi().then((res) => {
          if (res?.code === 200 && res?.user) {
            const { username, realname, userId, baseDept } = res.user
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }

            commit('SET_NAME', username)
            commit('SET_REALNAME', realname)
            commit('SET_USERID', userId)
            if (res.user?.baseDept) {
              commit('SET_BASEBRANCHINNERCODE', baseDept.branchinnercode)
            }
            if (res?.loginUser) {
              commit('SET_BASEDEPTCODE', res?.loginUser.baseDeptCode)
              commit('SET_BASEDEPTID', res?.loginUser.baseDeptId)
              commit('SET_BASEDEPTNAME', res?.loginUser.baseDeptName)
            }

            if (res.user?.dept?.name){
              commit('SET_BRANCHCODENAME', res.user.dept.name)
            }
            if (res.user?.dept?.branchcode){
              commit('SET_BRANCHCODE', res.user.dept.branchcode)
            }
            if (res.user?.dept?.branchinnercode){
              commit('SET_BRANCHINNERCODE', res.user.dept.branchinnercode)
            }
            if (res.user?.primaryDept?.name){
              commit('SET_PRIMARYDEPTNAME', res.user.primaryDept.name)
            }
            if (res.loginUser?.workStations?.length){
              commit('SET_WORKSTATIONS', res.loginUser.workStations)
            }
            resolve(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logoutApi().then((res) => {
          // if (res.code === 200) {
            commit('SET_TOKEN', '')
            commit('SET_CIDC_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            commit('SET_ALL_LIST', [])
            commit('PERMIT_LIST', [])
            commit('TREE_PERMIT_LIST', [])
            commit('SET_ADMIN_DETAIL', null);
            removeJSESSIONID();
            removeToken()
            removeCIDCToken()
            removeData("adminDetail")
            resolve()
          // }
        }).catch(error => {
          commit('SET_TOKEN', '')
          commit('SET_CIDC_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_ALL_LIST', [])
          commit('PERMIT_LIST', [])
          commit('TREE_PERMIT_LIST', [])
          commit('SET_ADMIN_DETAIL', null);
          removeJSESSIONID();
          removeToken()
          removeCIDCToken()
          removeData("adminDetail")
          resolve()
          reject(error)

        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_CIDC_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_ALL_LIST', [])
        commit('PERMIT_LIST', [])
        commit('TREE_PERMIT_LIST', [])
        commit('SET_ADMIN_DETAIL', null);
        removeJSESSIONID();
        removeToken()
        removeCIDCToken()
        removeData("adminDetail")
        resolve()
      })
    }
  }
}

export default user
